package cn.bdqn.controller.user;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

import cn.bdqn.service.user.UserService;
import cn.bdqn.pojo.User;
import cn.bdqn.tools.Constants;
import cn.bdqn.tools.PageSupport;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserService userService;
	private User user = null;
	
	@RequestMapping("/pwdmodify")
	public String modifypwd(){
		return "pwdmodify";
	}
	@RequestMapping("/pwdmodifysave")
	public String modifypwdSave(@RequestParam("newpassword") String newpassword,HttpSession session){
		user = (User) session.getAttribute(Constants.USER_SESSION);
		int id=user.getId();
		boolean a=userService.updatePwd(id, newpassword);
		if(a){
			return "login";
		}
		return "pwdmodify";
	}

	@RequestMapping(value = "/existuserpassword")
	@ResponseBody
	public Object existuserPassword(@RequestParam("oldpassword") String oldpassword, HttpSession session) {
		HashMap<String, String> map = new HashMap<String, String>();
		
		if (StringUtils.isNullOrEmpty(oldpassword)) {
			map.put("result", "error");
		} else {
			user = (User) session.getAttribute(Constants.USER_SESSION);
			if (user != null) {
				String pwd = user.getUserPassword();
				if (pwd.equals(oldpassword)) {
					map.put("result", "true");
				} else {
					map.put("result", "false");
				}
			} else {
				map.put("result", "sessionerror");
			}
		}
		return JSONArray.toJSONString(map);
	}

	/*
	 * @RequestMapping("/deleteUser") public String deleteUser(String uid){
	 * boolean a=userService.deleteUserById(Integer.parseInt(uid)); if(a){
	 * return "redirect:/user/userlist"; } return "error"; }
	 */
	// 使用ajax验证userCode是否存在
	@RequestMapping(value = "/existuserCode")
	@ResponseBody
	public Object existuserCode(@RequestParam("userCode") String userCode) {
		HashMap<String, String> resultMap = new HashMap<String, String>();

		if (StringUtils.isNullOrEmpty(userCode)) {
			resultMap.put("userCode", "exist");
		} else {
			user = userService.selectUserCodeExist(userCode);
			if (user != null) {
				resultMap.put("userCode", "exist");
			} else {
				resultMap.put("userCode", "noexist");
			}
		}
		return JSONArray.toJSONString(resultMap);
	}

	// 使用ajax删除用户
	@RequestMapping("/deleteUser")
	@ResponseBody
	public Object deleteUser(@RequestParam("uid") String uid,
			@RequestParam("uname") String uname) {
		String result = "";
		user = userService.selectUserNameExist(uname);
		if (user == null) {
			result = "noexist";
		} else {
			boolean a = userService.deleteUserById(Integer.parseInt(uid));
			if (a) {
				result = "true";
			} else {
				result = "false";
			}
		}
		return JSONArray.toJSON(result);
	}

	/*
	 * @RequestMapping("/viewUser") public String viewUser(String uid, Model m)
	 * { user = userService.getUserById(uid); SimpleDateFormat d = new
	 * SimpleDateFormat("yyyy年MM月dd"); String birthday =
	 * d.format(user.getBirthday()); m.addAttribute("user", user);
	 * m.addAttribute("birthday", birthday); return "userview"; }
	 */
	// 使用ajax实现
	@RequestMapping(value = "/viewUser.html"/*
											 * ,produces={
											 * "application/json;charset=UTF-8"}
											 */)
	@ResponseBody
	public User viewUser(String uid) {
		user = userService.getUserById(uid);
		return user;
	}

	/*
	 * public Object viewUser(String uid) { if(StringUtils.isNullOrEmpty(uid)){
	 * return "nodata"; } user = userService.getUserById(uid);
	 * System.out.println(JSONArray.toJSONString(user)); return
	 * JSONArray.toJSONString(user); }
	 */

	@RequestMapping(value = "/modfiyUser", method = RequestMethod.GET)
	public String modfiyUser(@RequestParam String uid, Model model) {
		user = userService.getUserById(uid);
		model.addAttribute("user", user);
		return "usermodify";
	}

	@RequestMapping(value = "/modfiyUserSave", method = RequestMethod.POST)
	public String modfiyUserSave(User user, HttpSession session) {
		user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION))
				.getId());
		user.setCreationDate(new Date());
		if (userService.modifyUser(user)) {
			return "redirect:/user/userlist";
		}
		return "usermodify";
	}

	@RequestMapping(value = "/addUser", method = RequestMethod.GET)
	public String addUser(@ModelAttribute("user") User user, HttpSession session) {
		if (session.getAttribute(Constants.USER_SESSION) == null) {
			return "login";
		}
		return "useradd";
	}


	@RequestMapping("/userlist")
	public String getUserlist(HttpServletRequest request, Model model) {
		// 查询用户列表
		String queryUserName = request.getParameter("queryname");
		String temp = request.getParameter("queryUserRole");
		String pageIndex = request.getParameter("pageIndex");
		int queryUserRole = 0;
		List<User> userList = null;
		// 设置页面容量
		int pageSize = Constants.pageSize;
		// 当前页码
		int currentPageNo = 1;
		if (queryUserName == null) {
			queryUserName = "";
		}
		if (temp != null && !temp.equals("")) {
			queryUserRole = Integer.parseInt(temp);
		}
		if (pageIndex != null) {
			try {
				currentPageNo = Integer.valueOf(pageIndex);
			} catch (NumberFormatException e) {
				return "redirect:error";
			}
		}
		// 总数量（表）
		int totalCount = userService.getUserCount(queryUserName, queryUserRole);
		// 总页数
		PageSupport pages = new PageSupport();
		pages.setCurrentPageNo(currentPageNo);
		pages.setPageSize(pageSize);
		pages.setTotalCount(totalCount);
		int totalPageCount = pages.getTotalPageCount();
		// 控制首页和尾页
		if (currentPageNo < 1) {
			currentPageNo = 1;
		} else if (currentPageNo > totalPageCount) {
			currentPageNo = totalPageCount;
		}
		int form = (currentPageNo - 1) * pageSize;
		userList = userService.getUserList(queryUserName, queryUserRole, form,
				pageSize);
		model.addAttribute("userList", userList);
		model.addAttribute("queryUserName", queryUserName);
		model.addAttribute("queryUserRole", queryUserRole);
		model.addAttribute("totalPageCount", totalPageCount);
		model.addAttribute("totalCount", totalCount);
		model.addAttribute("currentPageNo", currentPageNo);
		return "userlist";
	}

	@RequestMapping("/doLogin")
	public String dologin(HttpServletRequest request, Model m) {
		// 获取用户名和密码
		String userCode = request.getParameter("userCode");
		String userPassword = request.getParameter("userPassword");
		// 调用service方法，进行用户匹配
		user = userService.login(userCode, userPassword);
		if (null != user) {// 登录成功
			// 放入session
			request.getSession().setAttribute(Constants.USER_SESSION, user);
			// 页面跳转（frame.jsp）
			return "frame";
		} else {
			// 页面跳转（login.jsp）带出提示信息--转发
			m.addAttribute("error", "用户名或密码不正确");
			return "login";
		}
	}

	@RequestMapping("loginOut")
	public String loginOut(HttpServletRequest request) {
		// 清除session
		request.getSession().removeAttribute("userSucess");
		return "login";
	}
}
